package mobilesearch.thread;

import android.content.ContentResolver;
import mobilesearch.data.AudioData;
import mobilesearch.data.CallLogData;
import mobilesearch.ui.BroadcastCommand;

import java.util.ArrayList;
import android.database.Cursor;
import android.provider.CallLog;
import android.provider.MediaStore;
import android.util.Log;
import android.content.Intent;
import android.content.Context;

public class CallLogSearchThread extends Thread {
	
	private static final String TAG = "CallLogSearchThread";
	private ContentResolver resolver;
	private Context context;

	private String phoneNumber;
	private String date;
	
	public CallLogSearchThread(Context context, ContentResolver resolver) {
		super();
		this.context = context;
		this.resolver = resolver;
	}

	@Override
	public void run() {
		super.run();
		Log.i(TAG, "run()");
		ArrayList<CallLogData> callLogList = new ArrayList<CallLogData>();
		try{
			Cursor cursor = this.resolver.query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
			if(cursor.moveToFirst()){
				Log.i(TAG, "cursor.moveToFirst()");
				do{
					CallLogData data = new CallLogData();
					
					int phoneNumberIndex = cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL);
					this.phoneNumber = cursor.getString(phoneNumberIndex);
					if(this.phoneNumber == null){
						phoneNumberIndex = cursor.getColumnIndex(CallLog.Calls.NUMBER);
						this.phoneNumber = cursor.getString(phoneNumberIndex);
					}
					data.setPhoneNumber(this.phoneNumber);
					
					int dateIndex = cursor.getColumnIndex(CallLog.Calls.DATE);
					this.date = cursor.getString(dateIndex);
					data.setDate(this.date);
					
					callLogList.add(data);
				}while(cursor.moveToNext());
			}
		}catch(Exception exception){
			Log.i(TAG, exception.toString());
		}
		
		//broadcast the call log data
		Log.i(TAG, "search complete");
		if(!callLogList.isEmpty()){
			Log.i(TAG, "callLogList is not empty");
			Intent callLogIntent = new Intent(BroadcastCommand.SEARCH_CALLLOG);
			callLogIntent.putParcelableArrayListExtra(BroadcastCommand.SEARCH_CALLLOG, callLogList);
			this.context.sendBroadcast(callLogIntent);	
		}
	}
	
	
}
